package controller

import (
	"admin/contrib/session"
	"admin/model"
	"common/helper"
	"encoding/json"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strings"
	"time"
)

type WithdrawController struct{}

// 提现拒绝
type withdrawRejectParam struct {
	Code   string `json:"code"`
	ID     string `json:"id"`
	Remark string `json:"remark"`
}

// 提款审核
type withdrawReviewParam struct {
	ID string `json:"id"`
}

// /批量处理订单接收参数
type ProcessOrderPara struct {
	Ids    string `json:"ids"`
	Status string `json:"status"`
}

// 挂起/取消挂起
func (that *WithdrawController) Suspend(ctx *fasthttp.RequestCtx) {
	param := withdrawReviewParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("挂起/取消挂起", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
	}
	admin := session.AdminGet(ctx)
	record := g.Record{
		"confirm_at":  ctx.Time().Unix(),
		"withdraw_at": ctx.Time().Unix(),
		"confirm_uid": admin["id"],
	}
	successNum := 0
	failNum := 0
	for _, id := range orderIds {
		// 加锁
		err = model.WithdrawLock(id)
		if err != nil {

			failNum += 1
			continue
		}
		err = model.WithdrawSuspend(id, record)
		if err == nil {
			successNum += 1
		} else {
			failNum += 1
		}
		//解锁
		model.WithdrawUnLock(id)
	}
	retData := make(map[string]int)
	retData["success_total"] = successNum
	retData["faild_total"] = failNum

	helper.RetData(ctx, true, retData)
}

// 提交三方
func (that *WithdrawController) ToThird(ctx *fasthttp.RequestCtx) {
	param := withdrawReviewParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("提款订单提交三方", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" && admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	if admin["loginuser"] == "merchant" {
		operator, _ := model.GetOperatorInfoById(admin["id"])
		if operator.WithdrawButton == "0" {
			helper.RetData(ctx, false, "权限不足")
			return
		}
	}
	record := g.Record{
		"confirm_at":   ctx.Time().Unix(),
		"withdraw_at":  ctx.Time().Unix(),
		"confirm_uid":  admin["id"],
		"confirm_name": admin["name"],
		"state":        model.WithdrawDealing,
	}
	successNum := 0
	failNum := 0
	for _, id := range orderIds {
		// 加锁
		err = model.WithdrawLock(id)
		if err != nil {
			failNum += 1
			continue
		}
		err = model.WithdrawToThird(id, record)
		helper.InfoLog("提交三方：订单id--%s--%s", id, err)
		if err == nil {
			successNum += 1
		} else {
			failNum += 1
		}
		//解锁
		model.WithdrawUnLock(id)
	}
	retData := make(map[string]int)
	retData["success_total"] = successNum
	retData["faild_total"] = failNum

	helper.RetData(ctx, true, retData)
}

func (that *WithdrawController) ToThird123qwe(ctx *fasthttp.RequestCtx) {
	param := withdrawReviewParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("自动提款订单提交三方", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}
	helper.InfoLog("自动出款：订单id--%s", param.ID)
	record := g.Record{
		"confirm_at":  time.Now().Unix(),
		"withdraw_at": time.Now().Unix(),
		"confirm_uid": 0,
		"automatic":   2,
		"state":       model.WithdrawDealing,
	}
	err = model.WithdrawToThird(param.ID, record)
	if err != nil {
		helper.InfoLog("自动出款err：订单id--%s--%s", param.ID, err)
	}
	helper.RetData(ctx, true, "success")
}

func (that *WithdrawController) Check(ctx *fasthttp.RequestCtx) {
	param := withdrawReviewParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("审查提款订单提", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" && admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	if admin["loginuser"] == "merchant" {
		operator, _ := model.GetOperatorInfoById(admin["id"])
		if operator.WithdrawButton == "0" {
			helper.RetData(ctx, false, "权限不足")
			return
		}
	}
	record := g.Record{
		"confirm_at":   ctx.Time().Unix(),
		"withdraw_at":  ctx.Time().Unix(),
		"confirm_uid":  admin["id"],
		"confirm_name": admin["name"],
		"state":        model.WithdrawDealing,
	}
	msg, err := model.WithdrawToCheck(param.ID, record)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, msg)

	//successNum := 0
	//failNum := 0
	//for _, id := range orderIds {
	//	// 加锁
	//	//err = model.WithdrawLock(id)
	//	//if err != nil {
	//	//	failNum += 1
	//	//	continue
	//	//}
	//	msg, err := model.WithdrawToCheck(id, record)
	//	helper.RetData(ctx, true, msg)
	//	helper.InfoLog("审查三方：订单id--%s--%s", id, err)
	//	if err == nil {
	//		successNum += 1
	//	} else {
	//		failNum += 1
	//	}
	//	//解锁
	//	//model.WithdrawUnLock(id)
	//}
	//retData := make(map[string]int)
	//retData["success_total"] = successNum
	//retData["faild_total"] = failNum
	//
	//helper.RetData(ctx, true, retData)
}

// Reject 后台审核拒绝
func (that *WithdrawController) Reject(ctx *fasthttp.RequestCtx) {

	param := withdrawRejectParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("提款订单拒绝出款", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" && admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	if admin["loginuser"] == "merchant" {
		operator, _ := model.GetOperatorInfoById(admin["id"])
		if operator.WithdrawButton == "0" {
			helper.RetData(ctx, false, "权限不足")
			return
		}
	}
	record := g.Record{
		"confirm_at":   ctx.Time().Unix(),
		"withdraw_at":  ctx.Time().Unix(),
		"confirm_uid":  admin["id"],
		"confirm_name": admin["name"],
		"state":        model.WithdrawReviewReject,
	}
	if param.Remark != "" {
		record["review_remark"] = param.Remark
	}
	successNum := 0
	failNum := 0
	for _, id := range orderIds {
		err = model.WithdrawLock(id)
		if err != nil {
			failNum += 1
			continue
		}
		err = model.WithdrawFailOpt(id, record)

		if err == nil {
			successNum += 1
		} else {
			failNum += 1
		}
		//解锁
		model.WithdrawUnLock(id)
	}

	retData := make(map[string]int)
	retData["success_total"] = successNum
	retData["faild_total"] = failNum

	helper.RetData(ctx, true, retData)
}

// Reject 后台审核没收
func (that *WithdrawController) Confiscate(ctx *fasthttp.RequestCtx) {

	param := withdrawRejectParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("提款订单拒绝没收", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" && admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	if admin["loginuser"] == "merchant" {
		operator, _ := model.GetOperatorInfoById(admin["id"])
		if operator.WithdrawButton == "0" {
			helper.RetData(ctx, false, "权限不足")
			return
		}
	}
	record := g.Record{
		"confirm_at":   ctx.Time().Unix(),
		"withdraw_at":  ctx.Time().Unix(),
		"confirm_uid":  admin["id"],
		"confirm_name": admin["name"],
		"state":        model.WithdrawConfiscate,
	}
	if param.Remark != "" {
		record["review_remark"] = param.Remark
	}
	successNum := 0
	failNum := 0
	for _, id := range orderIds {
		err = model.WithdrawLock(id)
		if err != nil {
			failNum += 1
			continue
		}
		err = model.WithdrawFailOpt(id, record)

		if err == nil {
			successNum += 1
		} else {
			failNum += 1
		}
		//解锁
		model.WithdrawUnLock(id)
	}

	retData := make(map[string]int)
	retData["success_total"] = successNum
	retData["faild_total"] = failNum

	helper.RetData(ctx, true, retData)
}

// Review 审核
func (that *WithdrawController) Review(ctx *fasthttp.RequestCtx) {

	param := withdrawReviewParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("提款订单通过", ctx)

	orderIds := strings.Split(param.ID, ",")
	if orderIds == nil {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" && admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	if admin["loginuser"] == "merchant" {
		operator, _ := model.GetOperatorInfoById(admin["id"])
		if operator.WithdrawButton == "0" {
			helper.RetData(ctx, false, "权限不足")
			return
		}
	}
	record := g.Record{
		"confirm_at":   ctx.Time().Unix(),
		"withdraw_at":  ctx.Time().Unix(),
		"confirm_uid":  admin["id"],
		"confirm_name": admin["name"],
		"state":        model.WithdrawSuccessManual,
	}
	successNum := 0
	failNum := 0
	for _, id := range orderIds {
		err = model.WithdrawLock(id)
		if err != nil {
			failNum += 1
			continue
		}
		err = model.WithdrawSuccessOpt(id, record)

		if err == nil {
			successNum += 1
		} else {
			failNum += 1
		}
		//解锁
		model.WithdrawUnLock(id)
	}
	retData := make(map[string]int)
	retData["success_total"] = successNum
	retData["faild_total"] = failNum
	helper.RetData(ctx, true, retData)

}

func (that *WithdrawController) CallbackBetcat(ctx *fasthttp.RequestCtx) {

	model.WithdrawBetCatPayCallBack(ctx)
}

func (that *WithdrawController) CallbackU2c(ctx *fasthttp.RequestCtx) {

	model.WithdrawU2cPayCallBack(ctx)
}

func (that *WithdrawController) CallbackPay4(ctx *fasthttp.RequestCtx) {

	model.WithdrawPay4CallBack(ctx)
}

func (that *WithdrawController) CallbackJeepayW(ctx *fasthttp.RequestCtx) {

	model.WithdrawalJeepayCallBack(ctx)
}

func (that *WithdrawController) CallbackCepayW(ctx *fasthttp.RequestCtx) {

	model.WithdrawalCepayCallBack(ctx)
}

// ChannelList 支出通道
func (that *WithdrawController) ChannelList(ctx *fasthttp.RequestCtx) {
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	data, err := model.PayFactoryList(2)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}

// OrderList 转出记录+转出审核
func (that *WithdrawController) OrderList(ctx *fasthttp.RequestCtx) {

	param := model.RiskHistoryParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	param.ExportExcel = ctx.QueryArgs().GetUintOrZero("export_excel")
	if param.ExportExcel == 1 {
		param.Page = 1
		param.PageSize = model.ExportExcelPageSize
	}

	if param.Page < 1 {
		param.Page = 1
	}

	data, err := model.WithdrawList(param, ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	data, exportData := model.WithdrawListOpt(data, param.ExportExcel)

	if param.ExportExcel == 1 {
		exportTitle := []string{
			"订单ID",
			"玩家ID",
			"提款金额",
			"手续费",
			"实际到账",
			"状态",
			"提款时间",
		}
		filename := "提现记录-" + time.Now().Format("20060102150405")
		if model.ExportExcel(filename, exportTitle, exportData) == nil {
			helper.RetData(ctx, true, filename)
		} else {
			helper.RetData(ctx, false, helper.RequestFail)
		}

		return
	} else {
		helper.RetData(ctx, true, data)
		return
	}

}

func (that *WithdrawController) BankCardList(ctx *fasthttp.RequestCtx) {

	param := model.BankCardParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	if param.Page < 1 {
		param.Page = 1
	}

	if param.PageSize < 10 || param.PageSize > 3000 {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	data, err := model.BankCardList(param, ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}

func (that *WithdrawController) UpdateBankCard(ctx *fasthttp.RequestCtx) {
	param := model.MemberBankcard{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("银行卡更新删除", ctx)
	err = model.UpdateBankcard(param, 0)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, "成功")
}

func (that *WithdrawController) DeleteBankCard(ctx *fasthttp.RequestCtx) {
	param := model.MemberBankcard{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("银行卡删除", ctx)
	err = model.UpdateBankcard(param, 1)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, "成功")
}
